<template>
  <div v-drag>
    <div @click="closePopup(false)" class="mask"></div>
    <div class="edit_box" v-loading="loading">
      <div class="box_head">
        <p>{{ mid ? (Boolean(isDefine) ? '确认' : '修改') : '新增' }}换货单</p>
        <i @click="closePopup(false)"></i>
      </div>
      <div class="box_body">
        <!--        <div class="line" v-if="!mid&&!Boolean(wid)">-->
        <!--          <span class="lab"><i class="mark_icon">*</i>发起仓库：</span>-->
        <!--          <div :class="{'error_border':tip_num===2}">-->
        <!--            <el-select placeholder="请选择仓库" filterable v-model="sourceWarehouseId" >-->
        <!--              <el-option-->
        <!--                v-for="(item,index) in warehouseList"-->
        <!--                :key="index"-->
        <!--                :label="item.name"-->
        <!--                :value="item.id">-->
        <!--              </el-option>-->
        <!--            </el-select>-->
        <!--          </div>-->
        <!--        </div>-->
        <div class="line" v-if="!mid">
          <span class="lab"><i class="mark_icon">*</i>接收仓库：</span>
          <div :class="{'error_border':tip_num===1 && errKey==='warehouse'}">
            <el-select placeholder="请选择仓库" v-model="warehouseId" :popper-append-to-body="false" filterable>
              <el-option
                v-for="(item,index) in warehouseList"
                :key="index"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </div>
        </div>
        <div class="line">
          <div class="g-mt-10">
            <i @click="addVos()" class="el-icon-circle-plus-outline addlist" v-if="!Boolean(isDefine)"></i>
          </div>
        </div>
        <div class="line">
          <!--<span class="lab"></span>-->
          <div style="width: 100%">
            <div class="line_item" v-for="(item,index) in itemList">
              <div ref="input" :class="{'error_border':tip_num===index && errKey === 'productId'}">
                <el-select :disabled="Boolean(isDefine)" filterable placeholder="请选择商品" v-model="item.productId"
                           value-key="id" @focus="getIndex($event,index)">
                  <span v-if="item.productId == ''">
                  <el-option
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                    v-for="(item,index) in productList">
                  </el-option>
                    </span>

                  <span v-else>
                  <el-option
                    :key="item.id"
                    :label="item.name"
                    :value="item.id"
                    v-for="(item,index) in finalProductList">
                  </el-option>
                    </span>

                </el-select>
              </div>
              <div>
                <el-input :disabled="Boolean(isDefine)"
                          :min="backupsList[index].numbers"
                          onKeypress="return(/[\d.]/.test(String.fromCharCode(event.keyCode)))"
                          @focus="setTip('','','')"
                          placeholder="商品数" type="Number" v-model.number="item.numbers"
                          :class="{'error_border':tip_num===index && errKey === 'numbers'}">
                  <template slot="prepend">商品数</template>
                </el-input>
              </div>
              <div>
                <el-input :disabled="Boolean(isDefine)"
                          :min="backupsList[index].returnNumber"
                          onKeypress="return(/[\d.]/.test(String.fromCharCode(event.keyCode)))"
                          placeholder="回收数" type="Number" v-model.number="item.returnNumber">
                  <template slot="prepend">回收数</template>
                </el-input>
              </div>
              <span>
                <i @click="delVos(index)" class="el-icon-remove-outline" v-if="!item.id&&itemList.length>1"></i>
              </span>

            </div>
          </div>
        </div>
        <p class="error_line">{{ infoTip }}</p>
      </div>
      <div class="box_foot">
        <span @click="closePopup(false)">取消</span>
        <span @click="confirmDelivery" v-if="Boolean(isDefine)">确定</span>
        <span @click="confirmEdit" v-else>确定</span>
      </div>
    </div>
  </div>
</template>

<script>
import {
  BarterOrderConfirm,
  getBarterOrderDetail,
  updateBarterOrder,
  addBarterOrder
} from "@/api/basic/warehouse/barterOrder";
import {getOtherWarehouse} from "@/api/basic/warehouse";
import {getAllUser} from "@/api/sys/user";
import {listAllData} from "@/api/config/product";


export default {
  props: ['mid', 'isDefine', 'delivery', 'wid'],
  data() {
    return {
      menuName: '',
      userId: '',
      warehouseName: '',
      warehouseId: '',
      sourceWarehouseId: '',
      deliveryNo: this.delivery ? this.delivery : '',
      phone: '',
      parentMenu: [],
      proStatus: 1,
      warehouseList: [],
      sourceWarehouseList: [],
      userList: [],
      productList: [],
      itemList: [],
      backupsList: [],
      infoTip: '',
      tip_num: '',
      errKey: '',
      loading: false,
      finalProductList: [],
      isChange: true
    }
  },
  mounted() {
    this.getWarehouse(this.wid);
    this.getAllProduct();
    if (this.mid) {
      this.getDetail();
    } else {
      this.addVos();
    }
  },
  methods: {
    getIndex(e, index) {
      this.setTip('', '', '');
      this.itemList[index].productId = '';
      //重新获取当前的数据
      this.getNewAllProduct();
    },

    getDetail() {
      let that = this;
      this.loading = true;
      getBarterOrderDetail(this.mid).then(res => {
        that.setData(res);
        that.loading = false;
      }).catch((e) => {
        that.loading = false;
      });
    },


    //用户列表
    userData() {
      let that = this;
      getAllUser().then(res => {
        that.userList = res ? res : [];
      }).catch((e) => {
        that.userList = [];
      });
    },

    //商品列表
    getAllProduct(data) {
      let that = this;
      let queryParams = {}
      if (data) {
        queryParams.productIds = data;
      }
      listAllData(queryParams).then(res => {
        that.productList = res ? res : [];
        if (this.isChange) {
          this.finalProductList = res ? res : [];
          this.isChange = false;
        }
      }).catch((e) => {
        that.productList = [];
      })
    },

    //排除自己以外的仓库
    getWarehouse(id) {
      let that = this;
      getOtherWarehouse({warehouseId: id}).then(res => {
        if (res) {
          that.warehouseId = res[0].id;
          that.warehouseList = res;
        }
      })
    },

    getNewAllProduct() {
      // 重新获取列表
      let arr = []
      this.itemList.forEach((item, index) => {
        if (item.productId != '') {
          arr.push(item.productId)
        }
        return arr
      })
      arr = arr.join(',')
      this.getAllProduct(arr);
    },

    setData(obj) {
      this.itemList = obj.listDetail;
      this.backupsList = JSON.parse(JSON.stringify(obj.listDetail));
    },

    setWarehouseData(data) {
      this.warehouseName = data.name;
    },

    setUserData(data) {
      this.menuName = data.name;
    },

    // 确认编辑
    confirmEdit() {
      let that = this;
      if (!that.warehouseId) {
        that.setTip(1, 'warehouse', '请选择接收换货仓库!');
      } else {
        this.judgeItemList();
      }
    },
    //判断是否有相同商品
    judgeSame() {
      let that = this;
      let itemLen = this.itemList.length;
      if (itemLen <= 1) {
        this.sendInfo();
        return;
      }
      for (let i = 0; i < itemLen; i++) {
        let item = this.itemList[i];
        for (let j = i + 1; j < itemLen; j++) {
          let items = this.itemList[j];
          if (item.productId === items.productId) {
            this.setTip('', 'same', '不能选择两种相同的商品！');
            return;
          } else {
            if (j === (itemLen - 1)) {
              that.sendInfo();
            }
          }
        }

      }
    },
    //判断数组
    judgeItemList() {
      let itemListLen = this.itemList.length;
      for (let i = 0; i < itemListLen; i++) {
        let item = this.itemList[i];
        if (item.productId === '') {
          this.setTip(i, 'productId', '请选择商品!');
          return;
        } else if (item.numbers <= 0) {
          this.setTip(i, 'numbers', '商品数需大于0!');
          return;
        } else if ((itemListLen - 1) === i) {
          this.judgeSame();

        }
      }
    },

    confirmDelivery() {
      let that = this;
      that.loading = true;
      BarterOrderConfirm(that.mid).then(res => {
        that.closePopup(true);
        that.$message.success({
          message: '操作成功',
          duration: 1000
        });
      }).catch((e) => {
        that.loading = false;
      });
    },

    isEnough(data) {
      let num = 0;
      let that = this;
      for (let i = 0; i < data.length; i++) {
        if (data[i].productId) {
          num += data[i].numbers;
          data[i].returnNumbers = data[i].returnNumber
        } else {
          if (data.length > 1) {
            that.delVos(i);
            i--
          }
        }
      }
      return Boolean(num);
    },


    addVos() {
      // this.checkList();

      let data = {
        numbers: 0,
        productId: '',
        returnNumber: 0
      };
      this.itemList.push(data);
      this.backupsList.push(JSON.parse(JSON.stringify(data)))

    },

    delVos(index) {
      this.itemList.splice(index, 1);
      this.backupsList.splice(index, 1);
    },

    sendInfo() {
      let that = this;
      that.loading = true;
      let data = {
        deliveryNo: that.deliveryNo,
        warehouseId: that.warehouseId,
        sourceWarehouseId: that.wid,
        productInfo: that.itemList,
      };
      if (that.mid) {
        data.id = that.mid;
        updateBarterOrder(data).then(res => {
          that.closePopup(true);
          that.$message.success({
            message: '操作成功',
            duration: 1000
          });
        }).catch((e) => {
          that.loading = false;
        });
      } else {
        addBarterOrder(data).then(res => {
          that.closePopup(true);
          that.$message.success({
            message: '操作成功',
            duration: 1000
          });
        }).catch((e) => {
          that.loading = false;
        });
      }
    },

    setTip(num, key, text) {
      this.tip_num = num;
      this.infoTip = text;
      this.errKey = key;
    },

    // 关闭
    closePopup(refresh) {
      this.$emit('listenToChild', {refresh: refresh})
    }
  }
}
</script>

<style scoped>

.avatar-uploader .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}

.avatar-uploader .el-upload:hover {
  border-color: #60BAE7;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #DCDFE6;
  width: 100px;
  height: 100px;
  line-height: 100px;
  text-align: center;
  border: 1px solid #DCDFE6;
  border-radius: 6px;
}

.avatar {
  max-width: 210px;
  min-width: 60px;
  height: 100px;
  display: block;
  border-radius: 6px;
  margin-right: 15px;
  border: 1px solid #bbb;
}

.line_item {
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-bottom: 10px;
  width: 100%;
}

.line .line_item > div {
  width: 27% !important;
}

.line .line_item > span {
  display: block;
  width: 30px;
}

.line .line_item i, .addlist {
  font-size: 25px;
  color: #6687f9;
  cursor: pointer;
}
</style>
